<template>
  <div class="demo-collapse">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="用户基本信息" name="1">
        <img class="setting_avatar"
          :src="this.userForm.userPicPath == null ? require('@/assets/img/avatar.png') : this.userForm.userPicPath"
          @click="userPicDialogVisible = true" alt="" />
        <p style="margin-bottom: 20px; text-align: center">点击头像查看和修改</p>
        <div style="width: 800px; margin: auto">
          <el-form :model="userForm" label-width="120px" :disabled="!userFormEditing">
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" name="username" />
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="userForm.nickname" name="nickname" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="userForm.sex" size="large">
                <el-radio label="保密" name="保密">保密</el-radio>
                <el-radio label="女" name="女">女</el-radio>
                <el-radio label="男" name="男">男</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="说明">
              <el-input v-model="userForm.description" name="description" type="textarea" />
            </el-form-item>
          </el-form>
          <el-form-item label="编辑">
            <el-button :disabled="!userFormEditing" type="primary" @click="updateUserBaseInfo">确认</el-button>
            <el-button @click="userFormEditing = !userFormEditing">{{ userFormEditing ? '重制' : '修改' }}</el-button>
          </el-form-item>
        </div>
      </el-collapse-item>
      <el-collapse-item title="用户拓展信息" name="2">
        <div style="width: 800px; margin: auto">
          <p>邮箱设置</p><br>
          <el-input type="email" v-model="userForm.email" :disabled="!expandInfoEditing.emailEditing"
            placeholder="邮箱地址">
            <template #prepend>绑定邮箱</template>
            <template #append>
              <el-button icon="EditPen" @click="
  expandInfoEditing.emailEditing =
  !expandInfoEditing.emailEditing
">点击编辑</el-button>
            </template>
          </el-input>
          <el-input v-model="expandInfoEditing.email" placeholder="邮箱验证码" v-if="expandInfoEditing.emailEditing">
            <template #append>
              <el-button icon="Promotion">发送邮箱验证码</el-button>
            </template>
          </el-input>
          <div style="margin-bottom:20px"></div>
          <br>
          <el-button v-if="expandInfoEditing.emailEditing" type="primary">确认</el-button>
          <el-button v-if="expandInfoEditing.emailEditing">重制</el-button>
          <el-divider />
        </div>
        <div style="width: 800px; margin: auto">
          <p>手机号设置</p><br>
          <el-input v-model="userForm.number" :disabled="!expandInfoEditing.phoneEditing" placeholder="手机号">
            <template #prepend>绑定手机号</template>
            <template #append>
              <el-button icon="EditPen" @click="
  expandInfoEditing.phoneEditing =
  !expandInfoEditing.phoneEditing
">点击编辑</el-button>
            </template>
          </el-input>
          <el-input placeholder="手机号验证码" v-if="expandInfoEditing.phoneEditing">
            <template #append>
              <el-button icon="Promotion">发送手机号证码</el-button>
            </template>
          </el-input>
          <div style="margin-bottom:20px"></div>
          <br>
          <el-button v-if="expandInfoEditing.phoneEditing" type="primary">确认</el-button>
          <el-button v-if="expandInfoEditing.phoneEditing">重制</el-button>
          <el-divider />
        </div>
        <div style="width: 800px; margin: auto" v-if="userForm.role == '学生'">
          <p>用户所属设置</p><br>
          <el-form-item label="当前所在班级">
            <p v-if="!editingAppealForm">{{ userForm.areaFormatted }}</p>
          </el-form-item>
          <el-form v-loading="userForm.belong.split(',')[3]==-1" element-loading-text="你已提交了申请，正在受理中" 
          label-width="120px" v-if="editingAppealForm">
            <el-form-item label="所属高校">
              <el-select v-model="provinceValue" class="m-2" placeholder="选择所在省份" size="small"
                @change="provinceChanged(val)">
                <el-option v-for="area in province" :label="area.name" :key="area.areaId" :value="area.areaId" />
              </el-select>&nbsp;&nbsp;
              <el-select v-model="areaValue" class="m-2" placeholder="选择所在城市" size="small" @change="areaChanged()">
                <el-option v-for="area in areas" :label="area.name" :key="area.name" :value="area.name" />
              </el-select>&nbsp;&nbsp;
              <el-select v-model="collegeValue" class="m-2" placeholder="选择所在高校" size="small">
                <el-option v-for="item in college" :label="item.collegeName" :key="item.collegeId" :value="item.collegeId" />
              </el-select>&nbsp;&nbsp;
            </el-form-item>
            <el-form-item label="加入班级">
              <!-- <p v-if="userForm.group != null">{{ userForm.group.groupName }}</p> -->
              <el-autocomplete style="width:100%" :fetch-suggestions="queryGroupAsync"
                @select="groupHandleSelect" placeholder="输入班级名称自动搜索" v-model="searchGroup.groupName" />
            </el-form-item>
            <el-form-item label="申请说明">
              <el-input type="textarea" v-model="appealContent" />
            </el-form-item>
          </el-form>
          <el-form-item label="编辑">
            <el-button type="primary" @click="postAppeal" v-if="editingAppealForm&&userForm.belong.split(',')[3]==0">立即申请</el-button>
            <el-button type="default" v-if="userForm.belong.split(',')[3]>0" 
            @click="editAppealForm">{{!editingAppealForm?'修改':'重制'}}</el-button>
          </el-form-item>
        </div>
      </el-collapse-item>
      <el-collapse-item v-if="false" title="主页设置" name="3">
        <div style="width: 800px; margin: auto">
          <p>主页banner</p><br>
        </div>
      </el-collapse-item>
      <el-collapse-item title="安全设置" name="4">
        <div style="width: 800px; margin: auto">
          <p>密码设置</p><br>
          <el-form :model="userForm" label-width="120px" disabled="">
            <el-form-item label="密码">
              <el-input v-model="userForm.password" type="password" name="password" show-password />
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <el-dialog v-model="userPicDialogVisible" title="查看头像" style="max-width:700px;width:fit-content">
    <div style="width:fit-content;margin:auto">
      <el-avatar :size="250" :src="userPicSrc" @click="selectFileTrigger" />
      <input type="file" name="resourceFile" style="display:none" id="userPicSelect"
        @change="userPicChange($event.target.files[0])">
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userPicDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="userPicDialogVisible = false; uploadUserPic()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>

export default {
  data() {
    return {
      activeNames: ["1", "2", '3', '4'],
      userFormEditing: false,
      userForm: {
        username: "用户名",
        password: "密码",
        nickname: "昵称",
        description: "说什么",
        sex: "保密",
        email: null,
        number: null,
      },
      appealContent:'',
      appealObjId:0,
      editingAppealForm:false,
      searchGroup: { groupName: '' },
      expandInfoEditing: {
        emailEditing: false,
        email: null,
        phoneEditing: false,
        phone: false,
      },
      province: [],
      areas: [],
      college: [],
      provinceValue: "",
      areaValue: "",
      collegeValue: "",
      userPicDialogVisible: false,
      userPicSrc: null,
      picFile: null
    };
  },
  created() {
    this.getUserinfo()
    fetch("/location/province", { method: "get" }).then((resp) => {
      resp.json().then((data) => {
        this.province = data;
        this.provinceValue = 1;
        this.provinceChanged();
        this.areaChanged("北京市");
      });
    });
  },
  methods: {
    getUserinfo() {
      this.$store.dispatch("updateUser").then(() => {
        this.userForm = this.$store.state.user;
        this.userPicSrc = this.userForm.userPicPath
        this.editingAppealForm=!(this.userForm.belong.split(',')[3]>0)
        // console.log(this.userForm.belong.split(',')[3]>0,this.editingAppealForm);
      });
    },
    postAppeal(){
      this.$request.post('/appeal/appeal_write',{
        appealType:'学生',appealContent:this.appealContent,appealObjId:this.appealObjId,appealBelongId:this.collegeValue
      }).then(data=>{
        this.$ElMessage({
          message: data.success ? '申请成功' : '申请失败',
          type: data.success ? 'success' : 'error',
        })
        if(data.success){
          this.getUserinfo()
        }
      })
    },
    editAppealForm(){
      this.editingAppealForm=!this.editingAppealForm;
      if(!this.editingAppealForm){
        this.getUserinfo()
      }
    },
    queryGroupAsync(groupName, callback) {
      if (groupName == null || groupName == '' || this.collegeValue == '') return
      this.$request.get('/group/group_search?groupName=' + groupName + '&collegeId=' + this.collegeValue).then(data => {
        if (data.data.length==0) {
          this.$ElMessage({
            message:'没有找到这个班级',
            type:'error',
          })
        }
        let groupList = data.data
        let groupArray = []
        groupList.forEach(group => {
          groupArray.push({ value: group.groupName + ' ( ' + group.leader.nickname + ' ) ', link: group })
        })
        callback(groupArray)
      })
    },
    groupHandleSelect(selectGroup) { 
      // console.log(selectGroup); 
      this.appealObjId=selectGroup.link.groupId
    },
    provinceChanged() {
      fetch("/location/area?parentId=" + this.provinceValue, {
        method: "get",
      }).then((resp) => {
        resp.json().then((data) => {
          this.areas = data;
          this.college = [];
          this.areaValue = "";
          this.collegeValue=''
        });
      });
    },
    areaChanged() {
      fetch("/location/college?area=" + this.areaValue, { method: "get" }).then(
        (resp) => {
          resp.json().then((data) => {
            this.college = data;
            this.collegeValue = "";
          });
        }
      );
    },
    updateUserBaseInfo() {
      this.$request.post('/user/update_user_base', this.userForm).then(data => {
        // console.log(data);
        this.$ElMessage({
          message: data.success ? '修改成功' : '修改失败',
          type: data.success ? 'success' : 'error',
        })
        if (data.success) {
          this.userFormEditing = false
          this.getUserinfo()
        }
      })
    },
    userPicChange(picFile) {
      this.userPicSrc = window.URL.createObjectURL(picFile)
      this.picFile = picFile
    },
    uploadUserPic() {
      let formdata = new FormData()
      formdata.append('resourceFile', this.picFile)
      this.$fetchutil.uploadFile('/user/update_user_pic', formdata, callback => {
        this.$ElMessage({
          message: callback.success ? '头像上传成功' : '头像上传失败',
          type: callback.success ? 'success' : 'error',
        })
        if (callback.success) {
          this.getUserinfo()
        }
      })
    },
    selectFileTrigger() {
      document.getElementById('userPicSelect').click()
    }
  }
};
</script>

<style scoped>
.setting_avatar {
  width: 100px;
  height: 100px;
  display: block;
  margin: 20px auto 0px;
  border-radius: 50%;
}
</style>
